import { Component, OnInit } from "@angular/core";
import { NzNotificationService } from "ng-zorro-antd";
import { Router } from "@angular/router";
import { HttpServcie } from "../../../service/http.service";
import { Config } from "../../../service/config";
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { NzModalService, NzModalSubject } from "ng-zorro-antd";
import { InformationBean } from "./bean/information.bean";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
@Component({
  selector: "information-page",
  templateUrl: "information.html",
  styleUrls: ["information.scss"]
})
export class InformationPage implements OnInit {
  informationBean: InformationBean = new InformationBean();
  data: any;
  list: any = []; //返回的数据
  //总页数
  total: string;
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  currentModal: NzModalSubject;
  modelTitle = "新增";
  modal: any = 0;
  isAddVisible = false;
  isConfirmLoading = false;
  inContent: any = {};
  updateData: any = {};
  sysUser: any = JSON.parse(window.localStorage.getItem("user"));
  validateForm: FormGroup;
  titles : string;

  constructor(
    private httpServcie: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService
  ) {
    this.informationBean.pageSize = 10;
    this.informationBean.currentPage = 1;
    // if(this.sysUser.partyType!='4'){
    //   this.informationBean.createPartyId = JSON.parse(window.localStorage['user']).partyParentId;
    // }else{
    this.informationBean.createPartyId = JSON.parse(
      window.localStorage["user"]
    ).partyId;
    this.informationBean.parentId = JSON.parse(
      window.localStorage["user"]
    ).partyParentId;
    // }

    this.query();
  }
  //接收参数

  ngOnInit() { }
  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }
  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.list.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }
  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.informationBean.pageSize = event;
    this.informationBean.currentPage = 1;
    this.query();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.informationBean.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.informationBean.currentPage = event;
    this.query();
  }

  //关闭model框
  handleCancel = e => {
    console.log(e);
    this.isAddVisible = false;
  };

  //添加后返回的结果
  addOutPut(event) {
    this.isConfirmLoading = true;
    setTimeout(() => {
      /* destroy方法可以传入onOk或者onCancel。默认是onCancel */
      this.currentModal.destroy();
      this.isConfirmLoading = false;
      this.currentModal = null;
    }, 500);
    this.query();
  }
  //交验
  getFormControls(name) {
    return this.validateForm.controls[name];
  }

  query() {
    this.httpServcie.getInformationList(this.informationBean).subscribe(
      data => {
        if (data.status === 200) {
          this.list = data.data.list;
          this.total = data.data.total;
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }
  //添加
  add(titleTpl, contentTpl, footerTpl) {
    this.modelTitle = "添加";
    this.modal = 0;

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  update(titleTpl, contentTpl, footerTpl, type, data) {
    if (type == "d") {
      this.modelTitle = "详情";

    } else {
      this.modelTitle = "修改";
    }

    this.modal = 1;
    const updateList: any = [];

    if (data) {
      this.updateData = data;
    } else {
      this.list.forEach(element => {
        if (element.checked) {
          updateList.push(element);
          this.updateData = element;
        }
      });
      if (updateList.length > 1) {
        // 异常
        this._notification.create("warning", "警告提示", "只能选中一条数据！");
        return;
      }
      if (updateList.length == 0) {
        // 异常
        this._notification.create("warning", "警告提示", "请选中一条数据！");
        return;
      }
    }

    this.currentModal = this.modalService.open({
      title: titleTpl,
      content: contentTpl,
      footer: footerTpl,
      maskClosable: false,
      width: 900,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }
  delete() {
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element);
      }
    });

    if (deleteList.length == 0 || deleteList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }
    if (
      deleteList[0].createPartyId !=
      JSON.parse(window.localStorage["user"]).partyId ||
      deleteList[0].createUserId != JSON.parse(window.localStorage["user"]).id
    ) {
      this._notification.create("warning", "警告提示", "不是你创建的不能删除！");
      return;
    }

    this.modalService.confirm({
      title: "您是否确认要删除这项内容",
      content: "<b>一旦删除，无法还原</b>",
      onOk() {
        let ob = thiss.httpServcie.deleteInformation({ id: deleteList[0].id }); //批量删除
        ob.subscribe(
          () => {
            thiss._notification.create("success", "成功", "删除成功！");
            thiss.informationBean.currentPage = 1;
            thiss.query();
          },
          error => {
            this._notification.create("error", "错误提示", "删除失败！");
          }
        );
      },
      onCancel() { }
    });
  }

  //转发
  transfer() {
    const deleteList: any = [];
    const thiss: any = this;
    this.list.forEach(element => {
      if (element.checked) {
        deleteList.push(element);
      }
    });

    if (deleteList.length == 0 || deleteList.length > 1) {
      // 异常
      this._notification.create("warning", "警告提示", "请选中一条数据！");
      return;
    }
    if (
      deleteList[0].createPartyId ==
      JSON.parse(window.localStorage["user"]).partyId ||
      deleteList[0].createUserId == JSON.parse(window.localStorage["user"]).id
    ) {
      this._notification.create("warning", "警告提示", "自己的资讯不用转发！");
      return;
    }
    let infor = deleteList[0];
    infor.id = null;
    infor.createPartyId = JSON.parse(window.localStorage["user"]).partyId;
    infor.createUserId = JSON.parse(window.localStorage["user"]).id;

    this.httpServcie.addInformation(infor).subscribe(data => {
      if (data.status == 200) {
        this._notification.create("success", "提示", "转发成功");
        this.query();
      }
    });
  }

  downLoad(data) {
    if (data.fileUrls) {
      let urls = (data.fileUrls + "").split(",");
      urls.forEach(url => {
        this.download(url, data.title + "." + url.split(".")[1]);
      });
    } else {
      this._notification.create("warning", "警告提示", "没有附件");
    }
  }

  download(url, name) {
    let link = document.createElement("a");
    let body = document.querySelector("body");

    this.getBlob(Config.IP + Config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = "none";
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }
  // todetail(titleTpl, contentTpl, footerTpl, data) {
  //   this.inContent = data
  //   this.modelTitle = '正文';
  //   this.modal = 2;
  //   this.currentModal = this.modalService.open({
  //     title: titleTpl,
  //     content: contentTpl,
  //     footer: footerTpl,
  //     maskClosable: false,
  //     width: 900,
  //     style: {
  //       top: '20px'
  //     },
  //     onOk() {
  //       console.log('Click ok');
  //     }
  //   });
  // }
}
